package com.example.tass.licence;

import org.apache.catalina.core.ApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.*;
import java.util.Base64;

/**
 * 验签工具类
 */
//@Component
public class VerifyTools
{
    //非对称密钥算法
    private static final String KEY_ALGORITHM = "SHA1withRSA";
    
    //@Autowired
    private LicenceContent licenceContent;

    /**
     * 验签
     */
    /**
     * 验证签名是否有效
     * @param message       原始信息
     * @param signMessage   签名消息
     * @param publicKey     验签公钥
     * @return  验签结果
     * @throws Exception
     */
    public static boolean verify(byte[] message, byte[] signMessage, PublicKey publicKey) throws Exception {
        
        boolean flag = false;
        // 验证签名是否有效
        Signature signature;
        signature = Signature.getInstance(KEY_ALGORITHM);
        signature.initVerify(publicKey);
        signature.update(message);
        flag = signature.verify(Base64.getDecoder().decode(signMessage));
        
        // 验证是否在有效期内
        
        
        // 验证是IP地址是否在白名单内
        return flag;
    }
    
    public boolean verify1(String certPath,String licencePath) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {

        // 1. 获取验签用的公钥
        PublicKey publicKey = KeyTools.getPublicKeyFromCer();   
        
        // 2. 读取licence文件，获取签名值
        Signature signature = Signature.getInstance(KEY_ALGORITHM);
        signature.initVerify(publicKey);
        signature.update(licenceContent.getUser().getBytes());

        return signature.verify(Base64.getDecoder().decode(licenceContent.getSign().getBytes()));
    }
}


